package io.renren.modules.job.task.tms;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.utils.WeChatUtil;
import io.renren.modules.job.entity.AlreadySend;
import io.renren.modules.job.entity.LimitationLog;
import io.renren.modules.job.entity.LocationLimit;
import io.renren.modules.job.task.ITask;
import io.renren.modules.tms.dao.ShipmentMapper;
import io.renren.modules.tms.dao.TMSMapper;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 针对西安需要整改的问题，现在就是要获取所有的单子，如果单子一直未到达且超过设定时间，则需要对仓库进行企业微信提醒
 */
@Component("LimitationTask")
@Service
public class LimitationTask implements ITask {

    @Resource
    private TMSMapper tmsMapper;

    @Override
    public void run(String params) {

        // 查询近一个月的数据
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf  = new SimpleDateFormat("yyyy-MM-dd");
        String endTime = sdf.format(calendar.getTime());
        calendar.add(Calendar.MONTH, -1);
        String startTime = sdf.format(calendar.getTime());

        // 获取以西安为起始的运单，运单状态不为已到达
        List<LimitationLog> limitationLogList = tmsMapper.selectLimitation(startTime, endTime);

        List<AlreadySend> alreadySendList = tmsMapper.selectAlreadySendList();

        Map<String, String> alreadySendMap = new HashMap<>();

        alreadySendList.forEach(item -> {
            alreadySendMap.put(item.getShipmentNo() + "_" + item.getOrderNo(), "SEND");
        });

        // 如果为空，则不执行
        if (CollectionUtils.isEmpty(limitationLogList)){
            return;
        }

        // 获取两个地点的时间
        List<LocationLimit> locationLimits = tmsMapper.selectLocationLimit();
        if (CollectionUtils.isEmpty(locationLimits)){
            return;
        }

        List<StringBuilder> stringBuilders = new ArrayList<>();
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilders.add(stringBuilder);
        int MAX_COUNT = 16;
        int count = 0;

        // 判断是否超时效了
        for (LimitationLog limitationLog : limitationLogList) {
            if (limitationLog == null){
                continue;
            }

            String key = limitationLog.getShipmentNo() + "_" + limitationLog.getOrderNo();
            if (alreadySendMap.containsKey(key)){
                continue;
            }


            long maxTime = 48 * 60 * 60 * 1000;
            for (LocationLimit locationLimit : locationLimits) {
                if (limitationLog.getStartLocation().contains(locationLimit.getStartLocation())
                        || locationLimit.getStartLocation().contains(limitationLog.getStartLocation())){
                    if (limitationLog.getEndLocation().contains(locationLimit.getEndLocation())
                            || locationLimit.getEndLocation().contains(limitationLog.getEndLocation())){
                        maxTime = Long.parseLong(locationLimit.getMinTime()) * 60 * 60 * 1000;
                    }
                }
            }

            // 找到最小时间
            try {
                Date departTime = sdf.parse(limitationLog.getDepartTime());
                Date currentTime = new Date();
                long diffTime = departTime.getTime() + maxTime - 4 * 60 * 60 * 1000 - currentTime.getTime();
                // 严重超时的不预警
                if (diffTime < 0){
                    // 插入已发送表
                    alreadySendMap.put(key, "SEND");
                    tmsMapper.insertAlreadySend(limitationLog);
                    if (diffTime > - 4 * 60 * 60 * 1000) {
                        stringBuilder.append("运单号【").append(limitationLog.getShipmentNo()).append("】- 订单号【").append(limitationLog.getOrderNo()).append("】离到达截止时间已不足4小时，请尽快送达！").append("\n");
                    }else {
//                        stringBuilder.append("运单号【").append(limitationLog.getShipmentNo()).append("】- 订单号【").append(limitationLog.getOrderNo()).append("】已超时，请尽快送达！").append("\n");
                    }
                    count++;
                    if (count > MAX_COUNT){
                        count = 0;
                        stringBuilder = new StringBuilder();
                        stringBuilders.add(stringBuilder);
                    }
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        // 发企业微信给指定联系人
        String token = WeChatUtil.requestAccessToken();
        for (StringBuilder builder : stringBuilders) {
            String errorInfo = builder.toString();
            if (!StringUtils.isEmpty(errorInfo)){
                // 丁超
                WeChatUtil.sendMessage(token, errorInfo, "101190");
                // 高磊
//                WeChatUtil.sendMessage(token, errorInfo, "103045");
                // 沈新荣
//                WeChatUtil.sendMessage(token, errorInfo, "9346");
                // 田建宁
                WeChatUtil.sendMessage(token, errorInfo, "104848");
            }
        }

    }

}
